package com.studyyoun.android.nonghe.home.activity;
/**
 * Created by zhaolong on 2017/10/1.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.studyyoun.android.androidcommonbaselibrary.activity.CommonBaseActivity;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.client.OkhttpCommonClient;
import com.studyyoun.android.androidcommonbaselibrary.utils.ColorUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.CommonLoadingUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.DateUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.ToastUtils;
import com.studyyoun.android.androidcommonbaselibrary.view.FlowLayoutView;
import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.home.item.ItemArtDetaileOtherShareClass;
import com.studyyoun.android.nonghe.home.item.ItemArtDetaileRecommentShareClass;
import com.studyyoun.android.nonghe.home.model.ArtClassModel;
import com.studyyoun.android.nonghe.home.model.ArtModel;
import com.studyyoun.android.nonghe.home.sql.ArtSqlDBHelper;
import com.studyyoun.android.nonghe.http.HttpUrlHelper;
import com.studyyoun.android.nonghe.welcom.CommonUserHelper;
import com.studyyoun.android.nonghe.welcom.activity.LoginActivity;
import com.studyyoun.android.nonghe.welcom.model.UserModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * class infation
 */
public class ArtDetaileActivity extends CommonBaseActivity {

    private LinearLayout mBackLinearLayout;
    private TextView mHeaderTitleTextView;
    private ArtModel mArtModel;
    private TextView mArtTitleTextView;
    private TextView mAuthorTextView;
    private TextView mArtFlagTextView;
    private FlowLayoutView mFlowLayoutView;
    private WebView mArtWebView;


    private static final String APP_CACAHE_DIRNAME = "/wisdom/webcache";
    private TextView mIsTopTextView;
    private TextView mIsRecommendTextView;
    private TextView mArtRecomendTextView;
    private TextView mArtPariseTextView;
    private LinearLayout mArtPariseLinearLayout;
    private ArtSqlDBHelper mArtSqlDBHelper;
    private ImageView mArtPariseImageView;
    private String mArtModelId;
    private ImageView mArtPariseBottomImageView;
    private ItemArtDetaileRecommentShareClass mItemArtDetaileRecommentShareClass;
    private ImageView mArtToMycollectImageView;
    private ItemArtDetaileOtherShareClass mItemArtDetaileOtherShareClass;


    /**
     * 先根据上级传递的数据 mArtModel 来设置数据显示
     * 如果其为空，则根据上级传递的数据 artModelId 来加载网络数据
     *
     * @param intent
     */

    @Override
    protected void getAllIntentExtraDatas(Intent intent) {
        mArtModel = (ArtModel) intent.getSerializableExtra("artModel");
        if (mArtModel == null) {
            mArtModelId = intent.getStringExtra("artModelId");
        }
    }

    private long mPreLoadingTime = 0;

    /**
     * 加载文章详情 如果martModel为空
     *
     * @param artModelId
     */
    private void loadingArtModelDetailes(String artModelId) {
        CommonLoadingUtils.getInstance().showLoading(mArtTitleTextView);
        mPreLoadingTime = System.currentTimeMillis();

        String url = HttpUrlHelper.getArtDetailesFromeIdUrl;
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("id", artModelId);

        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(ArtModel.class) {
            @Override
            public void onSuccess(final Object obj) {
                long flagTime = System.currentTimeMillis() - mPreLoadingTime;
                if (flagTime < 2000) {
                    flagTime = 2000 - flagTime;
                } else {
                    flagTime = 0;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        CommonLoadingUtils.getInstance().closeFunction();
                        mArtModel = (ArtModel) obj;
                        setArtModelDetailsFunction();
                    }
                }, flagTime);

            }

            @Override
            public void onFaile(Object obj) {

                CommonLoadingUtils.getInstance().closeFunction();
                ToastUtils.show("加载文章详情失败 请重新进入 ", mContext);
            }
        });

    }

    @Override
    protected int getCommonLayoutId() {
        return R.layout.activity_art_detaile_layout;
    }

    @Override
    protected void commonInitView(View view) {

        mBackLinearLayout = findViewById(R.id.ll_base_back);
        mHeaderTitleTextView = findViewById(R.id.tv_base_header_title);
        mArtTitleTextView = findViewById(R.id.tv_art_des_title);
        mAuthorTextView = findViewById(R.id.tv_art_des_author);
        mArtFlagTextView = findViewById(R.id.tv_art_des_flag);
        mFlowLayoutView = findViewById(R.id.fv_art_class_flag);
        mIsTopTextView = findViewById(R.id.tv_home_item_art_is_top);
        mIsRecommendTextView = findViewById(R.id.tv_home_item_art_is_recommend);
        mArtRecomendTextView = findViewById(R.id.tv_home_item_art_is_seplse);


        //
        mArtPariseTextView = findViewById(R.id.tv_art_parise);
        mArtPariseImageView = findViewById(R.id.iv_art_parise);
        mArtPariseLinearLayout = findViewById(R.id.ll_art_parise);
        mArtPariseBottomImageView = findViewById(R.id.iv_botton_art_parise);

        //

        mArtToMycollectImageView = findViewById(R.id.iv_botton_art_my_colect);

        mArtWebView = findViewById(R.id.wv_art_content);

        mItemArtDetaileOtherShareClass = new ItemArtDetaileOtherShareClass(view, this, mHandler, mArtModel);

        /**
         * 文章评论相关操作
         */
        mItemArtDetaileRecommentShareClass = new ItemArtDetaileRecommentShareClass(view, this, mHandler, mArtModel);
    }

    @Override
    protected void commonFunction() {

    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            if (mArtModel == null) {
                if (TextUtils.isEmpty(mArtModelId)) {
                    ToastUtils.show("数据异常 请重新进入", mContext);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ArtDetaileActivity.this.finish();
                        }
                    }, 2000);
                    return;
                } else {
                    loadingArtModelDetailes(mArtModelId);
                }
            }
        }
    }

    @Override
    protected void commonDelayFunction() {

        if (mArtModel != null) {
            setArtModelDetailsFunction();
        }



    }

    private void setArtModelDetailsFunction() {

        if (mItemArtDetaileOtherShareClass != null) {
            mItemArtDetaileOtherShareClass.setArtmodel(mArtModel);
        }
        mArtSqlDBHelper = new ArtSqlDBHelper(mContext);

        mHeaderTitleTextView.setText("文章详情");
        mBackLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArtDetaileActivity.this.finish();
            }
        });

        mArtTitleTextView.setText(mArtModel.artName);
        mAuthorTextView.setText("作者：" + mArtModel.author + "\t\t创建分享于 " + DateUtils.getInstance().formatTime(Long.valueOf(mArtModel.artCreateTime)));
        mArtFlagTextView.setText(mArtModel.artFalg);

        if (mArtModel.artIsTop == 1) {
            mIsTopTextView.setVisibility(View.VISIBLE);
        } else {
            mIsTopTextView.setVisibility(View.GONE);
        }

        if (mArtModel.artIsRecommend == 1) {
            mIsRecommendTextView.setVisibility(View.VISIBLE);
        } else {
            mIsRecommendTextView.setVisibility(View.GONE);
        }
        if (mArtModel.specilModels != null && mArtModel.specilModels.size() > 0) {
            mArtRecomendTextView.setVisibility(View.VISIBLE);
            mArtRecomendTextView.setText(mArtModel.specilModels.get(0).getArtSpecilName());
        } else {
            mArtRecomendTextView.setVisibility(View.GONE);
        }

        //设置点赞
        List<String> articlPariseModels = mArtModel.articlPariseModels;
        if (articlPariseModels != null) {
            mArtPariseTextView.setText(String.valueOf(articlPariseModels.size())+"赞");
            UserModel userModel = CommonUserHelper.getUserModel();
            if (userModel != null) {
                if (articlPariseModels.contains(String.valueOf(userModel.getUserId()))) {
                    setPariseStatueFunction();
                } else {
                    setNoPariseStatueFunction();
                }
            } else {
                setNoPariseStatueFunction();
            }
        } else {
            mArtPariseTextView.setText("0赞");
            setNoPariseStatueFunction();
        }

        //设置收藏
        List<String> articCollectModels = mArtModel.articlCollectModels;
        if (articCollectModels != null) {

            UserModel userModel = CommonUserHelper.getUserModel();
            if (userModel != null) {
                if (articCollectModels.contains(String.valueOf(userModel.getUserId()))) {
                    mArtToMycollectImageView.setImageDrawable(getResources().getDrawable(R.mipmap.my_cllect_icon4));
                } else {
                    mArtToMycollectImageView.setImageDrawable(getResources().getDrawable(R.mipmap.my_cllect_icon3));
                }
            } else {
                mArtToMycollectImageView.setImageDrawable(getResources().getDrawable(R.mipmap.my_cllect_icon3));
            }
        } else {
            mArtToMycollectImageView.setImageDrawable(getResources().getDrawable(R.mipmap.my_cllect_icon3));
        }



        mArtPariseLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                UserModel userModel = CommonUserHelper.getUserModel();
                if (userModel == null) {
                    ToastUtils.show("请登录 ", mContext);
                    startActivity(new Intent(ArtDetaileActivity.this, LoginActivity.class));
                } else {
                    LogUtils.d("点赞");
                    ScaleAnimation scaleAnimation = new ScaleAnimation(1.5f, 1f, 1.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setDuration(400);
                    scaleAnimation.setInterpolator(new LinearInterpolator());
                    mArtPariseImageView.startAnimation(scaleAnimation);

                    paraiseFunction();
                }
            }
        });

        mArtPariseBottomImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UserModel userModel = CommonUserHelper.getUserModel();
                if (userModel == null) {
                    ToastUtils.show("请登录 ", mContext);
                    startActivity(new Intent(ArtDetaileActivity.this, LoginActivity.class));
                } else {
                    LogUtils.d("点赞");
                    ScaleAnimation scaleAnimation = new ScaleAnimation(1.5f, 1f, 1.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setDuration(400);
                    scaleAnimation.setInterpolator(new LinearInterpolator());
                    mArtPariseImageView.startAnimation(scaleAnimation);

                    paraiseFunction();
                }
            }
        });


        setMedieaFlowollFunction();
        webViewSettingFunction();
    }

    //点赞
    private void paraiseFunction() {
        List<String> articlPariseModels = mArtModel.articlPariseModels;
        UserModel userModel = CommonUserHelper.getUserModel();
        String userId = String.valueOf(userModel.getUserId());
        if (articlPariseModels != null && articlPariseModels.contains(userId)) {
            ToastUtils.show("您已点过赞了 ... ", mContext);
        } else {
            commitParaiseFunction(userId);
        }
    }

    private void commitParaiseFunction(final String userId) {
        String url = HttpUrlHelper.articlePairseUrl;
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("artId", String.valueOf(mArtModel.getId()));
        key.put("userId", userId);

        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
            @Override
            public void onSuccess(Object obj) {
                ToastUtils.show("点赞成功 ", mContext);
                List<String> articlPariseModels = mArtModel.articlPariseModels;
                if (articlPariseModels != null) {
                    articlPariseModels.add(userId);
                } else {
                    List<String> list = new ArrayList<String>();
                    list.add(userId);
                    mArtModel.articlPariseModels = list;
                }
                mArtSqlDBHelper.insertArt(mArtModel);

                mArtPariseTextView.setText(String.valueOf(articlPariseModels.size()));
                setPariseStatueFunction();
            }

            @Override
            public void onFaile(Object obj) {
                ToastUtils.show("点赞失败", mContext);
            }
        });
    }

    private void setPariseStatueFunction() {
        mArtPariseTextView.setTextColor(Color.parseColor("#F5A623"));
        mArtPariseBottomImageView.setImageDrawable(getResources().getDrawable(R.mipmap.art_parise2));
        mArtPariseImageView.setImageDrawable(getResources().getDrawable(R.mipmap.art_parise2));
        mArtPariseLinearLayout.setBackground(getResources().getDrawable(R.drawable.bg_art_parise_shape));
    }

    private void setNoPariseStatueFunction() {
        mArtPariseTextView.setTextColor(Color.parseColor("#969696"));
        mArtPariseBottomImageView.setImageDrawable(getResources().getDrawable(R.mipmap.art_parise5));
        mArtPariseImageView.setImageDrawable(getResources().getDrawable(R.mipmap.art_parise5));
        mArtPariseLinearLayout.setBackground(getResources().getDrawable(R.drawable.bg_art_no_parise_shape));
    }

    private void webViewSettingFunction() {

        initWebViewSettings(mArtWebView);
        String artContent = mArtModel.artContent;
        if (!TextUtils.isEmpty(artContent)) {
            String[] split = artContent.split("</head>");
            if (split.length == 2) {
                StringBuilder stringBuilder = new StringBuilder(split[0]);
                stringBuilder.append("<meta name=\"viewport\" content=\"width=divice-width,initial-scale=1.0\" >\n");
                stringBuilder.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/sample-css.css\"/> \n");
                stringBuilder.append("<style>html{margin:0;padding:0;font-family: sans-serif;font-size:14px} body{margin:10px;padding:0} img{width:80%;height:auto;}</style>");
                stringBuilder.append("</head>");
                stringBuilder.append(split[1]);
                LogUtils.d(stringBuilder.toString());
                artContent = stringBuilder.toString();

                if (artContent.contains("</body>")) {
                    String[] bodySpilt = artContent.split("</body>");
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append(bodySpilt[0]);

                    stringBuffer.append("<script type='text/javascript'>");
                    stringBuffer.append("var list = document.getElementsByTagName('img');");
                    stringBuffer.append("if (list != null) { ");


                    stringBuffer.append("for (var i = 0; i < list.length; i++) { ");
                    stringBuffer.append(" var im = list[i]; ");
                    stringBuffer.append("im.style.cssText = 'width:96%;height:auto;margin-left:1%;margin-rigth:1%;'");

                    stringBuffer.append("}");
                    stringBuffer.append("}");
                    stringBuffer.append("</script>");


                    stringBuffer.append("</body>");
                    stringBuffer.append(bodySpilt[1]);

                    artContent = stringBuffer.toString();
                }
                mArtWebView.loadDataWithBaseURL(null, artContent, "text/html", "utf-8",
                        null);
            } else {
                ToastUtils.show("数据异常,请重新进入", mContext);
            }

        } else {
            ToastUtils.show("数据异常,请重新进入", mContext);
        }


    }

    //设置标签
    private void setMedieaFlowollFunction() {
        DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
        float mScaledDensity = displayMetrics.scaledDensity;
        int paddingLeft = (int) (mScaledDensity * 8);
        int paddingTop = (int) (mScaledDensity * 2);


        for (int i = 0; i < mArtModel.articleClassModels.size(); i++) {
            //创建
            final TextView textView = new TextView(this);
            //设置frame
            textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            ArtClassModel artClassModel = mArtModel.articleClassModels.get(i);
            String artSpecilName = artClassModel.getArtClassName();
            //设置文字
            textView.setText(artSpecilName);
            //设置边框颜色
            int randomColor = ColorUtils.randomColor();
            //设置字体颜色
            textView.setTextColor(randomColor);
            //设置剧中
            textView.setGravity(Gravity.CENTER);
            //设置字体大小 为14pt
            textView.setTextSize(10);
            //设置内边距
            textView.setPadding(paddingLeft, paddingTop, paddingLeft, paddingTop);
            //设置背景
            Drawable normal = generateDrawable(randomColor, 4 * mScaledDensity);
            Drawable pressed = generatePressDrawable(randomColor, 24 * mScaledDensity);
            textView.setBackgroundDrawable(generateSelector(pressed, normal));
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String s = textView.getText().toString();
                    LogUtils.d("ss " + s);
                }
            });

            LinearLayout linearLayout = new LinearLayout(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER_VERTICAL;//设置居中显示
            linearLayout.setLayoutParams(layoutParams);
            //linearLayout.addView(textView);

            mFlowLayoutView.addView(textView);


        }
    }

    public static StateListDrawable generateSelector(Drawable pressed, Drawable normal) {
        StateListDrawable drawable = new StateListDrawable();
        drawable.addState(new int[]{android.R.attr.state_pressed}, pressed);//设置按下的图片
        drawable.addState(new int[]{}, normal);//设置默认的图片
        return drawable;
    }

    public GradientDrawable generateDrawable(int argb, float radius) {
        DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
        radius = radius * displayMetrics.scaledDensity;
        float mScaledDensity = displayMetrics.scaledDensity;
        int den = (int) (0.5 * mScaledDensity);
        if (den == 0) {
            den = 1;
        }
        GradientDrawable drawable = new GradientDrawable();
        drawable.setShape(GradientDrawable.RECTANGLE);//设置为矩形，默认就是矩形
        drawable.setStroke(den, argb);
        drawable.setCornerRadius(radius);//设置圆角的半径
        //drawable.setColor(argb);
        return drawable;
    }

    public GradientDrawable generatePressDrawable(int argb, float radius) {
        DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
        radius = radius * displayMetrics.scaledDensity;
        float mScaledDensity = displayMetrics.scaledDensity;
        int den = (int) (0.5 * mScaledDensity);
        if (den == 0) {
            den = 1;
        }
        GradientDrawable drawable = new GradientDrawable();
        drawable.setShape(GradientDrawable.RECTANGLE);//设置为矩形，默认就是矩形
        drawable.setStroke(den, argb);
        drawable.setCornerRadius(radius);//设置圆角的半径
        drawable.setColor(Color.parseColor("#eeeeee"));
        return drawable;
    }


    private void initWebViewSettings(WebView webView) {
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(false); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(false); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //设置缓冲大小，我设的是8M
        webSettings.setAppCacheMaxSize(1024 * 1024 * 105);

        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式

        // 开启 DOM storage API 功能

        webSettings.setDomStorageEnabled(true);


        //开启 database storage API 功能

        webSettings.setDatabaseEnabled(true);

        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;

//      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;


        //设置数据库缓存路径

        webSettings.setDatabasePath(cacheDirPath);

        //设置  Application Caches 缓存目录

        webSettings.setAppCachePath(cacheDirPath);

        //开启 Application Caches 功能

        webSettings.setAppCacheEnabled(true);

        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setBlockNetworkImage(false);
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.addJavascriptInterface(new ReadFinishClass(), "controll");

        //获取网页对话框
        webView.setWebChromeClient(mWebChromeClient);

        webView.setWebViewClient(new CustomWebViewClient());
    }

    public class ReadFinishClass {
        /**
         * 页面加载成功
         */
        @JavascriptInterface
        public void pageFinish(final float height) {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    LogUtils.d("设置 webview 大小 ");
                    mArtWebView.measure(0, 0);
                    // mArtWebView.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height*getResources().getDisplayMetrics().density)));
                }
            });
        }

    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            //构建一个来显示网页中的对话框
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            LogUtils.d("console message is " + consoleMessage.message() + "\n\t\t from line " + consoleMessage.lineNumber() + "\n\t\t of"
                    + consoleMessage.sourceId());
            return true;
        }

        //加载进度
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        //扩充缓存的容量
        //webview可以设置一个WebChromeClient对象，在其onReachedMaxAppCacheSize函数对扩充缓冲做出响应
        @Override
        public void onReachedMaxAppCacheSize(long spaceNeeded,
                                             long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {

        }

        /**
         * 当WebView加载之后，返回 HTML 页面的标题 Title
         * @param view
         * @param title
         */
        @Override
        public void onReceivedTitle(WebView view, String title) {


        }
    };

    private class CustomWebViewClient extends WebViewClient {
        private View mErrorView;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mArtWebView.loadUrl(url);
            return true;
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            LogUtils.e("webview  shouldInterceptRequest");
            return super.shouldInterceptRequest(view, request);

        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            LogUtils.e("webview  shouldInterceptRequest  url is " + url);
            return super.shouldInterceptRequest(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            LogUtils.d("web view loading start ");


        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);


            LogUtils.d("web view loading finish " + url);

            mArtWebView.getSettings().setBlockNetworkImage(false);
            // mMainWebView.loadUrl("javascript:readBookDesPageFinish(" + mArticleModel.id + ")");
            mArtWebView.loadUrl("javascript:controll.pageFinish(document.body.getBoundingClientRect().height)");

            //增加文章阅读次数
            if (CommonUserHelper.getUserModel() != null) {
                addUserReadArtReadCount(mArtModel.id);
            } else {
                addArtReadCount(mArtModel.id);
            }

            //加载评论信息
            mItemArtDetaileRecommentShareClass.loadingArtRecomment(mArtModel);

        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            if (error != null) {
                LogUtils.e("web view loading err  " + error.toString());
            }


        }


    }

    //增加文章阅读次数
    private void addArtReadCount(int id) {

        String url = HttpUrlHelper.sAddArticleReadCountFromIdUrl;

        ConcurrentHashMap<String, String> paramMap = new ConcurrentHashMap<>();

        paramMap.put("id", String.valueOf(id));

        OkhttpCommonClient.sentPostRequest(url, paramMap, new OkhttpCommonCallBack(null) {

            @Override
            public void onSuccess(Object obj) {
                LogUtils.d("增加文章阅读次数成功");
            }

            @Override
            public void onFaile(Object obj) {
                LogUtils.e("增加文章阅读次数失败");
            }
        });


    }

    private void addUserReadArtReadCount(int id) {

        String url = HttpUrlHelper.sAddUserReadArtRecodeFromIdUrl;

        ConcurrentHashMap<String, String> paramMap = new ConcurrentHashMap<>();

        paramMap.put("artId", String.valueOf(id));
        paramMap.put("userId", String.valueOf(CommonUserHelper.getUserModel().getUserId()));

        OkhttpCommonClient.sentPostRequest(url, paramMap, new OkhttpCommonCallBack() {

            @Override
            public void onSuccess(Object obj) {
                LogUtils.d("增加文章阅读次数成功");
            }

            @Override
            public void onFaile(Object obj) {
                LogUtils.e("增加文章阅读次数失败");
            }
        });


    }


}
